#include "../common.h"
using namespace std;
extern BuiltinCmd blt[MAX_BUILTIN_FUNC_NUM];
extern char buf[80];
extern char _obj[MAX_BUILTIN_DESC_LENGTH];
extern char _GIT[MAX_BUILTIN_DESC_LENGTH];
extern obj_index _index;
extern obj_index indexs[MAX_REFS_HEADS_NUMS];
extern char txt_index[MAX_BUILTIN_DESC_LENGTH];
char SHA_1[41];
char obj_sha[1024];
extern int indexnum;


int git_add() {
    BuiltinCmd x;
    strcpy(x.name, "add");
    strcpy(x.desc, "Add the staging area content to the warehouse");
    x.hasAction = true;
    x.optNum = 2;
    strcpy(x.Help,"git --add [file]");
	strcpy(x.action, "has been added to");
	addBuiltinCmd(&x);
//	strcpy(x.action[1],"Reinitialized existing Git repository in");
    return 0;
}
int get_sha(char *retv){
	getcwd(buf, sizeof(buf));
	char ch[1024];strcpy(ch,buf);
	strcat(ch,"\\"); strcat(ch,retv);
	strcpy(retv,ch);
//	printf("%s\n",retv[3]);
	FILE *fp=fopen("D:\\self-git\\git\\sha1\\sha.txt","w");
	fwrite(retv,1,strlen(retv),fp);
	fclose(fp);
	system("D:\\self-git\\git\\sha1\\sha1.exe");
	fp=fopen("D:\\self-git\\git\\sha1\\sha_write.txt","r");
	  fgets(SHA_1,41,fp);
	fclose(fp); 
}

int get_sha_path(char *SHA_1){
	strcpy(obj_sha,buf);
	strcat(obj_sha,"\\.git\\objects\\");
	char sha_2[41];strcpy(sha_2,SHA_1);
	memset(sha_2+2,0,sizeof(sha_2-2));
	strcat(obj_sha,sha_2);
	mkdir(obj_sha);
	strcat(obj_sha,"\\");
	strcpy(sha_2,SHA_1);
	memcpy(sha_2, sha_2+2, sizeof(sha_2)-2);
	strcat(obj_sha,sha_2);strcat(obj_sha,".dat");
//	printf("%s\n",obj_sha);	
}
int git_add_run(int retc,char **retv){
    _init();
	get_sha(retv[3]);
	get_sha_path(SHA_1);
	if (strcmp(SHA_1,"")==0)return 0;
	FILE *fp=fopen(obj_sha,"w");fclose(fp);
/*	
	FILE *fp=fopen(txt_index,"r");
	   fgets(_index->parent,41,fp);
	   fgets(_index->tree,41,fp);
	fclose(fp);
*/

	strcpy(_index.file_type,"blob");
	strcpy(_index.file_path,retv[3]);
	strcpy(_index.file_sha_path,obj_sha);
	strcpy(_index.tree,SHA_1);
	int pos=findtxt(retv[3],_index,SHA_1,obj_sha);
	printf("%d\n",pos);
	if (!pos){
		FILE *fp=fopen(txt_index,"a");
		fwrite(&_index,sizeof(_index),1,fp);
	    fclose(fp);
	}
	else{
		indexs[pos]=_index;
		FILE *fp=fopen(txt_index,"w");
		for (int i=1;i<=indexnum;i++)
		  fwrite(&indexs[i],sizeof(_index),1,fp);
	    fclose(fp);
	}
	//树形结构 
	/*
	if (!findtxt(retv[3],_index,SHA_1,obj_sha)){
		if (!_index->file_son){
			_index->file_son=(obj_index *)malloc(sizeof(obj_index)*1);
	        obj_index *p=_index->file_son;
			strcpy(p->file_path,retv[3]);
			strcpy(p->file_sha_path,obj_sha);
			strcpy(p->tree,SHA_1);
		}
		else
		for (obj_index *p=_index->file_son;p->file_next;p=p->file_next){
			p->file_next=(obj_index *)malloc(sizeof(obj_index)*1);
			p=p->file_next;
			strcpy(p->file_path,retv[3]);
			strcpy(p->file_sha_path,obj_sha);
			strcpy(p->tree,SHA_1);
		}
	}
	*/
}

